import React from 'react';
import {
    SafeAreaView,
    StyleSheet,
    ScrollView,
    View,
    Text,
    DeviceEventEmitter, TouchableWithoutFeedback, Image, TouchableOpacity, RefreshControl,
} from 'react-native';
import colors from '../../utils/colors';
import screen from '../../utils/screen';
import Images from '../../images/Images';
import {inject, observer} from 'mobx-react';
import {AppModal} from '../../widgets/modal';
import RequestUtil from '../../utils/RequestUtil';
import Api from '../../utils/Api';
import Constants from '../../utils/Constants';
import ShadowBoxView from '../../widgets/ShadowBoxView';
import VipUpChange from '../../components/VipUpChange';
import {getffly, getString} from '../../utils/common';
import AppEvent from '../../utils/AppEvent';


const getLevelImage = (level)=>{
    if(level === 1) return Images.level1
    if(level === 2) return Images.level2
    if(level === 3) return Images.level3
    if(level === 4) return Images.level4
    if(level === 5) return Images.level5
    if(level === 6) return Images.level6
    if(level === 7) return Images.level6
    if(level === 8) return Images.level6
    if(level === 9) return Images.level6
    if(level === 10) return Images.level6
    if(level === 11) return Images.level6
    if(level === 12) return Images.level6

}

@inject(['userStore'])
@observer
export default class Vip extends React.Component{


    state={
        data:null,
        isRefreshing:false
    }
    componentDidMount() {

        this.getData()
        this.listener = DeviceEventEmitter.addListener(AppEvent.update_vip,(data)=>{

            if(data && data.title){
                AppModal.showSuccess(data.title)
            }
            this.setState({
                data:null
            },()=>{
                this.getData()
            })
        })
    }
    componentWillUnmount() {
        this.listener && this.listener.remove()

    }

    getData(){

        AppModal.showLoading();
        this.setState({isRefreshing:true})
        RequestUtil.get(Api.vipData).then(res=>{
            console.log('vip',res)
            let data = res.data
            this.setState({
                data:data,
                isRefreshing:false
            })
            this.props.userStore.setUser(null,data)

            AppModal.hideTip()
        },error=>{
            this.setState({isRefreshing:false})
            AppModal.hideTip()
            console.log('vip error',error)
        })

    }

    showVipCharge(item){
        AppModal.showLoading();

        RequestUtil.get(Api.account).then(res=>{
            console.log('vip charge',res)
            let data = res.data
            AppModal.hideTip()
            this.vipUpDialog.show({...item,user_balance:data.user.balance})
        },error=>{
            AppModal.hideTip()
            console.log('vip charge error',error)
        })
    }


    renderHeader(){

        const {data} = this.state
        if(!data) return  null
        const {nickName} = this.props.userStore.userInfo
        let myLevel = data.myLevel
        let nameStr = nickName;
        if(nickName.length > 10) {
            nameStr = nickName.substring(0,10) + "...";
        }
        let taskLimit = 0
        let levelRes = data.levelList.find(item=>{
            return item.name === myLevel.name
        })
        if(levelRes){
            taskLimit = levelRes.dailyTaskLimit
        }

        return (
            <View style={styles.header}>
                <View>
                    <View style={{flexDirection: 'row',alignItems:'center'}}>
                        <Text style={ styles.appTitle  }>{nameStr}</Text>
                        <Image source={Images.vip_icon}
                               resizeMode={'contain'}
                               style={{width:screen.PIXEL_30,height:screen.PIXEL_40,marginHorizontal:screen.PIXEL_10}}
                        />
                        <Text style={{fontSize: 16,color:'#000'}}>Lv.{myLevel.name}</Text>
                    </View>
                    <Text style={{color:'#000',fontSize:13}}>{Constants.vip.daily_limit}:{taskLimit}</Text>
                    <Text style={{color:'#000',fontSize:13}}>{Constants.vip.valid_until}:{myLevel.expire ? myLevel.expire : Constants.vip.permanent}</Text>
                </View>
                <TouchableWithoutFeedback
                    onPress={()=>{
                        this.props.navigation.navigate('Order')
                    }}
                >
                    <Image source={Images.cart} style={styles.cart}/>
                </TouchableWithoutFeedback>
            </View>
        )
    }


    renderItem(item,index){

        // console.log('vip item',item)
        const {data} = this.state
        let isCurrent = data.myLevel.name === item.name
        let comstr = "";
        if(item.commission.length === 1) {
            comstr = item.commission[0] + "%";
        } else if(item.commission.length === 2) {
            if(item.commission[0] === item.commission[1]) {
                comstr = item.commission[0] + "%";
            } else {
                comstr = item.commission[0] + "-" + item.commission[1] + "%";
            }
        }

        let referralstr = ''
        if(item.referral && item.referral.length) {
            for(var i=0;i<item.referral.length;i++)
            {
                referralstr = referralstr + item.referral[i];
                if(i != item.referral.length-1)
                {
                    referralstr = referralstr + "    ";
                }
            }
        }
        let bottomView = null
        if(item.id > data.myLevel.id){
            if(item.upgradeMode == 'auto'){
                bottomView = (
                    <View style={{flexDirection: 'row',justifyContent:'space-between',alignItems:'center',marginTop:screen.PIXEL_20 }}>
                        <Text style={{color:'#000',fontSize: 13,flex:1}}>{Constants.vip.free_when_balance_reach + ' ' + Constants.appsymbol + item.upgrade[0].price}</Text>

                        <TouchableOpacity
                            style={{height:screen.scaleSize(66),backgroundColor:'#377C74',width:screen.PIXEL_230,
                                justifyContent:'center',alignItems: 'center',
                                borderRadius:screen.PIXEL_20,
                                borderBottomRightRadius: screen.PIXEL_40
                            }}
                            onPress={()=>{
                                this.props.navigation.navigate('Recharge')
                            }}
                        >
                            <Text style={{color:'#fff',fontSize: 16}}>{Constants.common.recharge}</Text>
                        </TouchableOpacity>
                    </View>
                )
            }else{
                bottomView = (
                    <View style={{flexDirection: 'row',justifyContent:'space-between',alignItems:'center',marginTop:screen.PIXEL_20 }}>
                        <Text style={{color:'#000',fontSize: 16}}>{Constants.appsymbol}
                            <Text style={{fontWeight: 'bold',fontSize:18 }}> {item.upgradeFee}</Text>
                        </Text>

                        <TouchableOpacity
                            style={{height:screen.scaleSize(66),backgroundColor:'#377C74',width:screen.PIXEL_230,
                                justifyContent:'center',alignItems: 'center',
                                borderRadius:screen.PIXEL_20,
                                borderBottomRightRadius: screen.PIXEL_40
                            }}
                            onPress={()=>{
                                this.showVipCharge(item)
                            }}
                        >
                            <Text style={{color:'#fff',fontSize: 17}}>{Constants.common.upgrade}</Text>
                        </TouchableOpacity>
                    </View>
                )
            }
        }

        return (
            <View style={{marginTop: 10}}
                  key={index.toString()}
            >
                <ShadowBoxView
                    shadowOption={{
                        radius:screen.PIXEL_40,
                        color:'#000',
                        x:0,
                        y:0,
                        border:5
                    }}
                >
                    <View style={styles.cardItem}>
                        <View style={{flexDirection: 'row'}}>
                            <Image source={getLevelImage(item.id)}
                                   resizeMode={'contain'}
                                   style={{width:screen.PIXEL_80,height:screen.PIXEL_80,marginRight:screen.PIXEL_20}}
                            />
                            <Text style={{color:'#000',fontSize: 18,fontWeight: 'bold'}}>Lv.{item.name}</Text>

                        </View>

                        <View style={{flexDirection: 'row',justifyContent: 'space-between'}}>
                            <View style={{flex:1}}>
                                <Text style={{fontSize: 15,color:'#000'}}>{Constants.vip.daily_orders}</Text>
                                <Text style={{fontSize: 15,color:'#FF7B14',fontWeight: 'bold'}}>{item.dailyTaskLimit}</Text>
                                <Text style={{fontSize: 15,color:'#000'}}>{Constants.vip.commission}</Text>
                                <Text style={{fontSize: 15,color:'#FF7B14',fontWeight: 'bold'}}>{comstr}</Text>

                            </View>

                            <View style={{flex:1}}>
                                <Text style={{fontSize: 15,color:'#000'}}>{Constants.vip.daily_withdraw}</Text>
                                <Text style={{fontSize: 15,color:'#FF7B14',fontWeight: 'bold'}}>{Constants.appsymbol + item.withdrawal.perOrder + " × " + item.withdrawal.limitCount}</Text>
                                <Text style={{fontSize: 15,color:'#000'}}>{Constants.vip.team_reward}</Text>
                                <Text style={{fontSize: 15,color:'#FF7B14',fontWeight: 'bold'}}>{referralstr}</Text>

                            </View>


                        </View>

                        {bottomView}

                        {
                            isCurrent && (
                                <View style={styles.currentTagBg}>
                                    <Text style={{fontSize:13 ,color:'#fff'}}>{Constants.vip.current}</Text>
                                </View>
                            )
                        }

                    </View>

                </ShadowBoxView>
            </View>
        )

    }

    render(){
        const {data,isRefreshing} = this.state
        return (
            <View style={styles.container}>
                <View style={styles.content}>
                    {this.renderHeader()}

                    {
                        data && (
                            <ScrollView
                                style={{flex:1,marginBottom:10}}
                                contentContainerStyle={{
                                    paddingVertical:screen.PIXEL_20,
                                    paddingHorizontal:screen.PIXEL_40,
                                }}
                                refreshControl = {
                                    <RefreshControl
                                        refreshing={ isRefreshing }
                                        onRefresh = {() => {
                                            this.getData()
                                        }}
                                    />
                                }
                            >
                                {
                                    data.levelList.map((item,index)=>{
                                        return this.renderItem(item,index)
                                    })
                                }
                            </ScrollView>
                        )
                    }

                </View>

                <VipUpChange
                    ref={ref=>{
                        this.vipUpDialog = ref
                    }}
                />
            </View>
        )
    }
}




const styles = StyleSheet.create({
    container: {
        flex:1,
        backgroundColor:colors.tabBgColor
    },
    content:{
        flex:1,backgroundColor: '#fff',
        borderBottomLeftRadius:screen.PIXEL_110,
        borderBottomRightRadius:screen.PIXEL_110,
        paddingTop:screen.statusBarHeight
    }, header:{
        flexDirection:'row',
        justifyContent:'space-between',
        paddingHorizontal:screen.PIXEL_60,
        marginVertical:screen.PIXEL_10
    },
    appTitle:{
        color:'#000',fontSize:19,fontWeight:'bold'
    },
    cart:{
        width:screen.scaleSize(73),
        height:screen.scaleSize(94)
    },
    cardItem:{
        width:'100%',backgroundColor:'#fff',
        borderRadius:screen.PIXEL_40,padding:screen.PIXEL_30,
    },
    currentTagBg:{
        position:'absolute',top:0,right:0,width:screen.PIXEL_220,
        height:screen.PIXEL_60,backgroundColor:'#FD7315',
        justifyContent: 'center',alignItems:'center',
        borderTopLeftRadius:screen.PIXEL_20,
        borderBottomLeftRadius: screen.PIXEL_20,
        borderTopRightRadius:screen.PIXEL_40
    }
})
